<?php

if( !defined('BASE_PATH') )
{
	define('BASE_PATH_TMP', dirname(dirname(__FILE__) ) ); 
	require_once BASE_PATH_TMP.'/include.php';
	require_once BASE_PATH_TMP.'/Library/TextDealer.php';
	require_once BASE_PATH_TMP.'/Library/phpQuery.php';
}

class NewsTools
{
	function __construct()
	{
	}

	static $_instance = null;
	static function getInstance()
	{
		if( self::$_instance === null )
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}
    
    function getJumpUrl2( $id )
    {
        $url = "http://view.inews.qq.com/a/{$id}";
        $info = file_get_contents( $url );
        $tourl = '';
        if( preg_match( '/article_url:\'([^\']*)\'/', $info , $arr ) )
        {
            $tourl = $arr[1];
        }
        else
        {
            throw new Exception( "找不到id:{$id}对应的底层页地址." );
            return;
        }
        return $tourl;
    }
    
    function getJumpUrl( $id )
    {
        // http://digi.tech.qq.com/a/20130315/000027.htm
        // http://view.inews.qq.com/a/DIG2013031500002712
        $pre = $this->getSitePre( $id );
        $date = substr( $id, 3, 8 );
        $aid = substr( $id, 11, 6 );
        return "http://{$pre}.qq.com/a/{$date}/{$aid}.htm";
    }
    
    function getRootID( $id )
    {
        $newsInfos = array();
        $this->selectInfo( array( $id ), $newsInfos );
        if( isset( $newsInfos[$id] ) && isset( $newsInfos[$id]['rootid'] ) && $newsInfos[$id]['rootid'] )
        {        
            //$this->info( "from db.". $newsInfos[$id]['rootid'] );
            return $newsInfos[$id]['rootid'];
        }
         
        $gourl = NewsTools::getInstance()->getJumpUrl( $id );
        if( !$gourl ) return false;
        $url = "http://tcomment.qq.com/wb/essrtex/fetchAction?l=1&cn=1&url={$gourl}";
        $url = "http://tcomment.qq.com/wb/rt/fetchAction?type=latest&url={$gourl}&page=1&pagesize=10&id=&time=";
        $info = file_get_contents( $url );
        $ret = json_decode( $info , true );
        if( ! $ret )
        {
            throw new Exception( "url:{$url}对应的热门评论获取失败." );
            return;
        }
        if( ! trim( $ret['rootID'] ) )
        {
            throw new Exception( "url:{$url}没有对应的根微博." );
        }
        $ret['rootID'] = number_format( $ret['rootID'], 0, '', '' );
        $r = $this->storeInfo( array( array( 'id'=>$id, 'rootid'=>$ret['rootID'] ) ) );
        if( $r )
        { 
            $this->info( "from url.". $ret['rootID'] );
            return $ret['rootID'];
        }
        return false;
    }
    
    function getCommentID( $id )
    {
        $r = $this->getNews( $id );
        if( $r['ret'] != 0 )
        {
            throw new Exception( "id:{$id}没有对应的评论id." );
        }
        return $r['newslist'][0]['commentid'];
    }
    
    function getNews( $id )
    {
        $info = file_get_contents( "http://inews.qq.com/getQQNewsListItems?ids=".$id );
        $ret = json_decode( $info, true );
        return $ret;
    }
    
    function getContent( $id )
    {
        $url = "http://inews.qq.com/getQQNewsNormalHtmlContent?id={$id}&chlid=".$this->getChlid( $id );
        $info = file_get_contents( $url );
        $ret = json_decode( $info, true );
        $ret['surl'] = $url;
        return $ret;
    }
    
    function getChlid( $id )
    {
        $pre = substr( $id, 0, 3 );
        $arr = array( 
            'news_news_top'=>'NEW',
            'news_news_finance_yaowen'=>'FIN',
            'news_news_ent'=>'ENT',
            'news_news_sports'=>'SPO',
            'news_news_tech'=>'TEC',
            'news_news_mil'=>'MIL',
            'news_news_digi'=>'DIG',
            'news_news_lad'=>'LAD',
            'news_news_auto'=>'AUT',
            'news_news_house'=>'HOS',
            'news_news_game'=>'GAM',
            'news_news_astro'=>'AST',
            'news_news_wx'=>'WXN',
            'news_news_gd'=>'GDC',
            'news_photo'=>'PIC',
            'news_video'=>'VDO',
            );
        $tmp = $arr;
        foreach( $tmp as $k=>$one )
        {
            $arr[$one] = $k;
        }
        
        if( isset( $arr[$pre] ) )
        {
            return $arr[$pre];            
        }
        else
        {
            throw new Exception( "id[{$id}]找不到对应的频道。" );
        }
    }
    
    function getSitePre( $id )
    {
        $pre = substr( $id, 0, 3 );
        $arr = array( 
        //    'news_news_top'=>'NEW',     // 不固定
            'finance'=>'FIN',
            'ent'=>'ENT',
            'sports'=>'SPO',
            'tech'=>'TEC',
            'news'=>'MIL',
            'digi.tech'=>'DIG',
            'lady'=>'LAD',
            'auto'=>'AUT',
            'house'=>'HOS',
            'games'=>'GAM',
            'astro.lady'=>'AST',
        //    'news_news_wx'=>'WXN',      // 频道来源不固定
            'gd'=>'GDC',
        //    'news'=>'PIC',              // 频道非常多，大部分是news的
        //    'news_video'=>'VDO',
            );
        $tmp = $arr;
        foreach( $tmp as $k=>$one )
        {
            $arr[$one] = $k;
        }
        
        if( isset( $arr[$pre] ) )
        {
            return $arr[$pre];            
        }
        else
        {
            throw new Exception( "id[{$id}]找不到对应的子站id。" );
        }
    }
    
    function getCommentList( $id, $page=1 )
    {    
        $cmd_id = NewsTools::getInstance()->getCommentID( $id );
        $chlid = NewsTools::getInstance()->getChlid( $id );
        $url = "http://inews.qq.com/getQQNewsComment?page={$page}&comment_id={$cmd_id}&url=http%3A%2F%2Fview.inews.qq.com%2Fa%2F{$id}&article_id={$id}&chlid={$chlid}";
        
        $str = file_get_contents( $url );
        if( $str == '' )
        {
            throw new Exception( "打开评论列表失败" );
        }
        $arr = json_decode( $str, true );
        return $arr;
    }
    
    function info( $obj )
    {
        Module::getInstance()->info( $obj );
    }
    
    function getNewsInfoFromDB( $ids )
    {
        $infos = array();
        $file = BASE_PATH."/Library/news.ini";
        $tmpIds = array();
        $newsInfo = array();
        if( ! is_file( $file ) ) 
        {
            $this->info( "file:{$file},is not exist." );
        } 
        else 
        {
            $r = $this->selectNews( $ids, $newsInfo );
            if( ! $newsInfo )
            {
                $tmpIds = $ids;
                $newsInfo = array();
            } 
            else 
            {
                foreach( $ids as $id )
                {
                    if( ! isset($newsInfo[$id]) || ! $newsInfo[$id] ) {
                        $tmpIds[] = $id;
                    } else {
                        $infos[$id] = $newsInfo[$id];
                    }
                }
                if( !$tmpIds ) {
                    return $infos;
                }
            }
        }
       
        if( ! $tmpIds ) return $infos;
        
        $this->info( "use cgi, news count:".count( $tmpIds ) );
        $ret = $this->getNewsList( $tmpIds );
        
        $tmp = array();
        $toget = $ret['newslist'];
        foreach( $toget as $one )
        {
            $tmp[$one['id']] = $one['title'];
        }
        
        $r = $this->storeNews( $ret['newslist'] );
        
        $toreturn = array_merge( $infos, $tmp );
        return $toreturn;
    }
    
    function selectNews( $ids, &$newsInfo )
    {
        $arr = array();
        if( $ids ) foreach( $ids as $id )
        {
            $id = stripslashes( $id );
            $arr[] = "'{$id}'";
        }
        $sql = "select * from t_news where id in (".implode(',', $arr ).")";
        $r = DBTls::getInstance()->select( $sql, $results );
        if( $r && $r['ret'] )
        {
            $tmp = $results;
            if( $tmp ) foreach( $tmp as $one )
            {
                $newsInfo[$one['id']] = $one['title'];
            }
        }
        else
        {
            $this->info( "select failed.sql:{$sql},ret=".print_r( $r, true ) );
        }
        return $r;
    }
    
    function storeNews( $infos )
    {
        if( $infos ) foreach( $infos as $one )
        {
            $one['id'] = mysql_escape_string( $one['id'] );
            $one['id'] = addslashes( $one['id'] );
            $one['title'] = mysql_escape_string( $one['title'] );
            $one['title'] = addslashes( $one['title'] );
            $arr[] = "('{$one['id']}','{$one['title']}')";
        }
		else
		{
			return array('ret'=>false, 'info'=>'null to store');
		}
        $sql = "insert into t_news (id,title) values".implode(',', $arr)."";
        $r = DBTls::getInstance()->query( $sql );
        if( $r['ret'] == false )
        {
            $this->info( "store failed.ret:".serialize( $r ).",sql:{$sql}" );
        }
        return $r;
    }
    
    function selectInfo( $ids, &$newsInfo )
    {
        $arr = array();
        if( $ids ) foreach( $ids as $id )
        {
            $id = stripslashes( $id );
            $arr[] = "'{$id}'";
        }
        $sql = "select * from t_news where id in (".implode(',', $arr ).")";
        $r = DBTls::getInstance()->select( $sql, $results );
        if( $r && $r['ret'] )
        {
            $tmp = $results;
            if( $tmp ) foreach( $tmp as $one )
            {
                $newsInfo[$one['id']] = $one;
            }
        }
        else
        {
            $this->info( "select failed.sql:{$sql},ret=".print_r( $r, true ) );
        }
        return $r;
    }
    
    function storeInfo( $infos )
    {
        if( $infos ) foreach( $infos as $one )
        {
            $r = $this->storeOne( $one );
            if( !$r || !$r['ret'] )
            {
                throw new Exception( "update error: ".serialize( $one ) );
            }
        }
        return true;
    }    
    
    function storeOne( $one )
    {
        $sql = "select * from t_news where id='{$one['id']}'";
        $results = array();
        $r = DBTls::getInstance()->select( $sql, $results );
        if( $r['ret'] && $results )
        {
            $id = $one['id'];
            unset( $one['id'] );
            $arr = array();
            foreach( $one as $k=>$v )
            {
                $v = mysql_escape_string( $v );
                $v = addslashes( $v );
                $arr[] = "{$k}='{$v}'";
            }
            
            $sql = "update t_news set ".implode( ',', $arr )." where id='{$id}'";
            $r = DBTls::getInstance()->update( $sql );
            return $r;
        }
        else
        {
            $fields = array();
            $values = array();
            $tostore = array( 'id', 'rootid', 'cmt_id', 'title' );
            foreach( $tostore as $fid )
            {
                if( isset( $one[$fid] ) )
                {
                    $one[$fid] = mysql_escape_string( $one[$fid] );
                    $one[$fid] = addslashes( $one[$fid] );
                    $fields[] = $fid;
                    $values[] = "'" . $one[$fid] . "'";
                }
            }
            
            $sql = "insert into t_news (".implode( ',', $fields ).") values(".implode( ',', $values ).")";
            $r = DBTls::getInstance()->insert( $sql );
            return $r;
        }
    }
    
    function getNewsInfo( $ids )
    {
        $infos = array();
        $file = BASE_PATH."/Library/news.ini";
        $tmpIds = array();
        $newsInfo = array();
        if( ! is_file( $file ) ) 
        {
            $this->info( "file:{$file},is not exist." );
        } 
        else 
        {
            $newsInfo = json_decode( file_get_contents( $file ), true );
            if( ! $newsInfo )
            {
                $tmpIds = $ids;
                $newsInfo = array();
            } 
            else 
            {
                foreach( $ids as $id )
                {
                    if( ! isset($newsInfo[$id]) || ! $newsInfo[$id] ) {
                        $tmpIds[] = $id;
                    } else {
                        $infos[$id] = $newsInfo[$id];
                    }
                }
                if( !$tmpIds ) {
                    return $infos;
                }
            }
        }
       
        if( ! $tmpIds ) return $infos;        
        $ret = $this->getNewsList( $tmpIds );
        
        $tmp = array();
        $toget = $ret['newslist'];
        foreach( $toget as $one )
        {
            $tmp[$one['id']] = $one['title'];
        }
        
        $todown = array_merge( $newsInfo, $tmp );
        file_put_contents( $file, json_encode( $todown ) );
        
        $toreturn = array_merge( $infos, $tmp );
        return $toreturn;
    }
    
    function getOneNew( $id )
    {
        $info = file_get_contents( "http://inews.qq.com/getQQNewsListItems?ids=".urlencode( $id ) );
        $ret = json_decode( $info, true );
        return $ret;
    }    
    
    function getNewsList( $ids )
    {
        $len = count( $ids );
        $infos = array('ret'=>0, 'newslist'=>array());
        for( $i=0; $i<$len; $i+=50 )
        {
            $tmpIds = array_slice( $ids, $i, 50 );
			$this->info( __FILE__ . __LINE__ ."to get news count:".count( $tmpIds ) );
            $iurl = "http://inews.qq.com/getQQNewsListItems?ids=".urlencode( implode(',', $tmpIds) );
			$this->info( $iurl );
            $info = file_get_contents( $iurl );
            $ret = json_decode( $info, true );
			if( !$ret || $ret['ret'] != 0 ) break;
            $infos['newslist'] = array_merge( $infos['newslist'], $ret['newslist'] );
        }
        return $infos;
    }
    
    function write_ini_file($assoc_arr, $path, $has_sections=FALSE) 
    { 
        $content = ""; 
        if ($has_sections) { 
            foreach ($assoc_arr as $key=>$elem) { 
                $content .= "[".$key."]\n"; 
                foreach ($elem as $key2=>$elem2) { 
                    if(is_array($elem2)) 
                    { 
                        for($i=0;$i<count($elem2);$i++) 
                        { 
                            $content .= $key2."[] = \"".$elem2[$i]."\"\n"; 
                        } 
                    } 
                    else if($elem2=="") $content .= $key2." = \n"; 
                    else $content .= $key2." = \"".$elem2."\"\n"; 
                } 
            } 
        } 
        else { 
            foreach ($assoc_arr as $key=>$elem) { 
                if(is_array($elem)) 
                { 
                    for($i=0;$i<count($elem);$i++) 
                    { 
                        $content .= $key2."[] = \"".$elem[$i]."\"\n"; 
                    } 
                } 
                else if($elem=="") $content .= $key2." = n"; 
                else $content .= $key2." = \"".$elem."\"\n"; 
            } 
        } 
        if (!$handle = fopen($path, 'w')) { 
            return false; 
        } 
        if (!fwrite($handle, $content)) { 
            return false; 
        } 
        fclose($handle); 
        return true; 
    }

}

if( isset($argv) && isset($argv[0]) && $argv[0] == basename( __FILE__ ) )
{
}
